package com.example.usercenter.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.example.usercenter.common.ErrorCode;
import com.example.usercenter.exception.BusinessException;
import com.example.usercenter.mapper.UserMapper;
import com.example.usercenter.model.domain.User;
import com.example.usercenter.service.UserService;
import jakarta.annotation.Resource;
import jakarta.servlet.http.HttpServletRequest;

import java.util.Collections;

import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;

import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.stream.Collectors;

import static com.example.usercenter.constant.userConstant.ADMIN_ROLE;
import static com.example.usercenter.constant.userConstant.USER_LOGIN_STATE;

/**
 * @author mi
 * @description 针对表【user】的数据库操作Service实现
 * @createDate 2024-06-05 16:50:47
 */
@Service
@Slf4j
public class UserServiceImpl extends ServiceImpl<UserMapper, User>
        implements UserService {

    /**
     * 加盐
     */
    private static final String SALT = "DK";

    //    @Autowired
    @Resource
    private UserMapper userMapper;

    @Override
    public long userRegister(String userAccount, String userPassword, String checkPassword, String planetCode) {
        //1.校验
        if (StringUtils.isAnyBlank(userAccount, userPassword, checkPassword, planetCode)) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "参数为空");
        }
        if (userAccount.length() < 4) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "用户账号过短");
        }
        if (userPassword.length() < 8 || checkPassword.length() < 8) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "用户密码过短");
        }
        if (planetCode.length() > 5) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "星球编号过长");
        }

        //账户不能使用特殊字符
        //使用正则表达式
        String validPattern = "^[a-zA-Z0-9_-]{3,20}$";
        Matcher matcher = Pattern.compile(validPattern).matcher(userAccount);
        boolean matches = matcher.matches();
        if (!matches) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "账户不能使用特殊字符");
        }

        //校验账户不能重复
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("userAccount", userAccount);
        long count = userMapper.selectCount(queryWrapper);
        if (count > 0) {
            throw new BusinessException(ErrorCode.ACCOUNT_REPEATED_ERROR);
        }
        //校验星球编号不能重复
        queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("planetCode", planetCode);
        count = userMapper.selectCount(queryWrapper);
        if (count > 0) {
            throw new BusinessException(ErrorCode.PLANET_CODE_REPEATED_ERROR);
        }
        //检验两次密码是否相同
        if (!StringUtils.equals(userPassword, checkPassword)) {
            throw new BusinessException(ErrorCode.PASSWORD_NOT_MATCH_ERROR);
        }


        //加密
        String encryptPassword = DigestUtils.md5DigestAsHex((SALT + userPassword).getBytes());

        //插入数据
        User user = new User();
        user.setUserAccount(userAccount);
        user.setUserPassword(encryptPassword);
        user.setPlanetCode(planetCode);
//        userMapper.insert()
        boolean saveResult = this.save(user);
        if (!saveResult) {
            throw new BusinessException(ErrorCode.INSERT_DATA_ERROR);
        }
        return user.getId();
    }

    @Override
    public User userLogin(String userAccount, String userPassword, HttpServletRequest request) {

        //1.校验
        if (StringUtils.isAnyBlank(userAccount, userPassword)) {
//            return ResultUtils.error(ErrorCode.NULL_ERROR);
            throw new BusinessException(ErrorCode.NULL_ERROR);
        }
        if (userAccount.length() < 4) {
//           return ResultUtils.error(ErrorCode.ACCOUNT_SHORT_ERROR);
            throw new BusinessException(ErrorCode.ACCOUNT_SHORT_ERROR);
        }
        if (userPassword.length() < 8) {
//            ResultUtils.error(ErrorCode.ACCOUNT_LONG_ERROR);
            throw new BusinessException(ErrorCode.ACCOUNT_LONG_ERROR);
        }

        //账户不能使用特殊字符
        //使用正则表达式
        String validPattern = "^[a-zA-Z0-9_-]{3,20}$";
        Matcher matcher = Pattern.compile(validPattern).matcher(userAccount);
        boolean matches = matcher.matches();
        if (!matches) {
//            ResultUtils.error(ErrorCode.ACCOUNT_FORMAT_ERROR);
            throw new BusinessException(ErrorCode.ACCOUNT_FORMAT_ERROR);
        }


        //加密
        String encryptPassword = DigestUtils.md5DigestAsHex((SALT + userPassword).getBytes());
        //查询用户是否存在
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("userAccount", userAccount);
        queryWrapper.eq("userPassword", encryptPassword);
        User user = userMapper.selectOne(queryWrapper);
        //用户不存在
        if (null == user) {
            log.info("user login failed, userAccount cannot match userPassword");
//            ResultUtils.error(ErrorCode.ACCOUNT_PASSWORD_ERROR);
            throw new BusinessException(ErrorCode.ACCOUNT_PASSWORD_ERROR);
        }

        //用户脱敏,隐藏敏感信息，防止数据库字段泄漏给前端
        User safetyUser = getSafetyUser(user);

        //记录用户的登陆状态
        request.getSession().setAttribute(USER_LOGIN_STATE, user);

        //返回脱敏后的信息
        return safetyUser;
    }


    @Override
    public List<User> userSearchByUserName(String userName, HttpServletRequest request) {

        if (!isAdmin(request)) {
            return Collections.emptyList();
        }
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        if (StringUtils.isNotBlank(userName)) {
            queryWrapper.like("userName", userName);
        }
        List<User> users = userMapper.selectList(queryWrapper);
        return users.stream().map(this::getSafetyUser).collect(Collectors.toList());

    }

    @Override
    public boolean userDeleteById(long id, HttpServletRequest request) {
        if (!isAdmin(request)) {
            throw new BusinessException(ErrorCode.DELETE_DATA_ERROR);
        }
        if (id <= 0) {
            throw new BusinessException(ErrorCode.DELETE_DATA_ERROR);
        }
        int result = userMapper.deleteById(id);
        return result > 0;
    }

    /**
     * 获取用户信息
     *
     * @param request
     * @return
     */
    @Override
    public User getCurrentUser(HttpServletRequest request) {
        Object attribute = request.getSession().getAttribute(USER_LOGIN_STATE);
        User currentUser = (User) attribute;
        if (currentUser == null) {
            return null;
        }
        Long userId = currentUser.getId();
        //TODO 校验用户是否合法
        User user = userMapper.selectById(userId);
        return this.getSafetyUser(user);
    }

    /**
     * 是否为管理员
     *
     * @param request
     * @return
     */
    private static boolean isAdmin(HttpServletRequest request) {
        Object attribute = request.getSession().getAttribute(USER_LOGIN_STATE);
        User userAttribute = (User) attribute;
        return userAttribute != null && userAttribute.getUserRole() == ADMIN_ROLE;
    }

    /**
     * 用户脱敏
     *
     * @param user
     * @return
     */
    @Override
    public User getSafetyUser(User user) {
        if (user == null) {
            return null;
        }
        User safetyUser = new User();
        safetyUser.setId(user.getId());
        safetyUser.setUserName(user.getUserName());
        safetyUser.setUserAccount(user.getUserAccount());
        safetyUser.setPlanetCode(user.getPlanetCode());
        safetyUser.setAvatarUrl(user.getAvatarUrl());
        safetyUser.setGender(user.getGender());
        safetyUser.setPhone(user.getPhone());
        safetyUser.setEmail(user.getEmail());
        safetyUser.setUserRole(user.getUserRole());
        safetyUser.setCreateTime(user.getCreateTime());
        safetyUser.setUpdateTime(user.getUpdateTime());
        return safetyUser;
    }

    /**
     * 用户注销
     *
     * @param request
     * @return
     */
    @Override
    public Integer userOutLogin(HttpServletRequest request) {
        request.getSession().removeAttribute(USER_LOGIN_STATE);
        return 1;
    }
}




